import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { CommunityPost as PostType } from '../../types/community';
import { Avatar, message, Modal } from 'antd';
import { formatDistanceToNow, isAfter, subMonths } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { HeartOutlined, HeartFilled, FireOutlined, StarOutlined, VerticalAlignTopOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { RootState } from '../../store';
import { getLikeStatus, likeAction } from '../../api/communityPostLikeController';
import { listCommunityTags } from '../../api/communityTagController';
import { deletePost } from '../../api/communityPostController';

interface Tag {
  id: string;
  tagcode: number;
  tagnamezh: string;
  createtime: string;
  updatetime: string;
}

interface Props {
  post: PostType;
  sectionId: string;
  onRefreshList: () => void;
}

const CommunityPost: React.FC<Props> = ({ post, sectionId, onRefreshList }) => {
  const navigate = useNavigate();
  const [isLiked, setIsLiked] = useState(false);
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const [tags, setTags] = useState<Tag[]>([]);
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
  
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const oneMonthAgo = subMonths(new Date(), 1);
    
    // 如果日期在一个月之内
    if (isAfter(date, oneMonthAgo)) {
      return formatDistanceToNow(date, { 
        addSuffix: true,
        locale: zhCN 
      });
    }
    
    // 如果超过一个月，显示完整日期
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  useEffect(() => {
    const getLikeStatusFromServer = async () => {
      try {
        if (loginUser.id) {
          const response = await getLikeStatus({ postId: Number(post.id) });
          if (response.code === 200) {
            setIsLiked(response.data);
          }
        }
      } catch (error) {
        console.error('Failed to get like status:', error);
      }
    };

    getLikeStatusFromServer();
  }, [post.id, loginUser.id]);

  useEffect(() => {
    const fetchTags = async () => {
      try {
        const response = await listCommunityTags();
        if (response.code === 200) {
          setTags(response.data);
        }
      } catch (error) {
        console.error('Failed to fetch tags:', error);
      }
    };
    fetchTags();
  }, []);

  const getTagName = (tagCode: number) => {
    const tag = tags.find(t => t.tagcode === tagCode);
    return tag?.tagnamezh || '';
  };

  const getTagStyle = (tagCode: number) => {
    switch (tagCode) {
      case 1: // 置顶
        return 'bg-red-100 text-red-600';
      case 2: // 热门
        return 'bg-rose-100 text-rose-600';
      case 3: // 推荐
        return 'bg-yellow-100 text-yellow-600';
      default:
        return 'bg-blue-100 text-blue-600';
    }
  };

  const renderTagIcon = (tagCode: number) => {
    switch (tagCode) {
      case 1: // 置顶
        return <VerticalAlignTopOutlined className="ml-1 text-red-500" />;
      case 2: // 热门
        return <FireOutlined className="ml-1 text-rose-500" />;
      case 3: // 推荐
        return <StarOutlined className="ml-1 text-yellow-500" />;
      default:
        return null;
    }
  };

  const handleLike = async (e: React.MouseEvent) => {
    e.stopPropagation();
    
    if (!loginUser.id) {
      message.warning('请先登录后再点赞');
      return;
    }
    
    try {
      const response = await likeAction({
        postId: Number(post.id),
        like: !isLiked
      });

      if (response.code === 200) {
        message.success(isLiked ? '已取消点赞' : '点赞成功');
        setIsLiked(!isLiked);
        onRefreshList();
      }
    } catch (error) {
      console.error('Failed to update like status:', error);
      message.error('操作失败，请稍后重试');
    }
  };

  const handlePostClick = () => {
    navigate(`/community/${sectionId}/post/${post.id}`, {
      state: { post }
    });
  };

  const handleEdit = (e: React.MouseEvent) => {
    e.stopPropagation();
    navigate(`/community/post/edit`, {
      state: { 
        isEdit: true, 
        post: post  // 直接传递整个 post 对象
      }
    });
  };

  const isCurrentUserPost = () => {
    return String(loginUser.id) === String(post.userVo.id);
  };

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsDeleteModalVisible(true);
  };

  const confirmDelete = async () => {
    try {
      const response = await deletePost({
        id: Number(post.id)
      });
      
      if (response.code === 200) {
        message.success('删除成功');
        onRefreshList();
      } else {
        message.error('删除失败');
      }
    } catch (error) {
      console.error('Failed to delete post:', error);
      message.error('删除失败，请稍后重试');
    } finally {
      setIsDeleteModalVisible(false);
    }
  };

  return (
    <>
      <div 
        className="bg-white rounded-lg p-6 shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer relative"
        onClick={handlePostClick}
      >
        <div className="flex items-start space-x-4">
          <Avatar src={post.userVo.avatarUrl} size={40} />
          <div className="flex-1">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <h3 className="text-lg font-medium">{post.title}</h3>
                {post.tagcode && (
                  <div className="flex items-center">
                    <span className={`px-2 py-1 text-xs rounded ${getTagStyle(post.tagcode)}`}>
                      {getTagName(post.tagcode)}
                    </span>
                    {renderTagIcon(post.tagcode)}
                  </div>
                )}
              </div>
              <div className="flex items-center space-x-4">
                {isCurrentUserPost() && (
                  <div className="flex space-x-2">
                    <button
                      onClick={handleEdit}
                      className="p-1.5 hover:bg-yellow-50 rounded-full transition-colors"
                      title="编辑"
                    >
                      <EditOutlined className="text-yellow-500 text-lg" />
                    </button>
                    <button
                      onClick={handleDelete}
                      className="p-1.5 hover:bg-red-50 rounded-full transition-colors"
                      title="删除"
                    >
                      <DeleteOutlined className="text-red-500 text-lg" />
                    </button>
                  </div>
                )}
                <span className="text-gray-500 text-sm">
                  {formatDate(post.createtime)}
                </span>
              </div>
            </div>
            <div className="mt-1">
              <span className="text-gray-600">{post.userVo.nickName}</span>
            </div>
            <div className="mt-3 text-gray-800">
              {post.content.length > 200 
                ? `${post.content.slice(0, 200)}...` 
                : post.content}
            </div>
            <div className="mt-4 flex items-center space-x-4 text-gray-500">
              <span>👁️ {post.viewcount}</span>
              <button
                onClick={handleLike}
                className={`flex items-center hover:text-red-500 transition-colors ${
                  isLiked ? 'text-red-500' : 'text-gray-500'
                } ${!loginUser.id ? 'cursor-not-allowed opacity-50' : ''}`}
                disabled={!loginUser.id}
              >
                {isLiked ? <HeartFilled /> : <HeartOutlined />}
                <span className="ml-1">{post.likecount}</span>
              </button>
              <span>💬 {post.commentcount}</span>
            </div>
          </div>
        </div>
      </div>

      <Modal
        title="确认删除"
        open={isDeleteModalVisible}
        onOk={confirmDelete}
        onCancel={(e) => {
          e.stopPropagation();
          setIsDeleteModalVisible(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <p>确定要删除这篇帖子吗？此操作不可恢复。</p>
      </Modal>
    </>
  );
};

export default CommunityPost; 